from django.contrib.auth.backends import ModelBackend
import re
from .models import User


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写authenticate方法"""

        # 提取参数
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            try:
                user = User.objects.get(mobile=username)
            except Exception as e:
                return None

        if user.check_password(password):
            return user
        else:
            return None